package com.mars.framework.exception;

import com.mars.common.constant.Constant;
import com.mars.common.result.R;
import com.mars.common.util.JsonUtils;
import com.mars.common.util.LoggerUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mars.common.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author 程序员Mars
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public R<String> exceptionHandler(HttpServletRequest request, Exception exception) {
        LoggerUtils.error("服务器异常，稍后重试={},", request.getRequestURL(), exception);
        return R.error("服务器异常，稍后重试");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<String> methodNotSupportHandler(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        LoggerUtils.error("不支持的请求方法={},", request.getRequestURL(), e);
        return R.error("不支持的请求方法");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return R.error(message);
    }

    @ExceptionHandler(value = {ServiceException.class})
    public R serviceExceptionHandler(HttpServletRequest request, ServiceException serviceException) {
        R message = new R<>(serviceException.getCode(), serviceException.getMsg(), null);
        serviceException.printStackTrace();
        LoggerUtils.error("业务异常={},接口响应={}", request.getRequestURL(), JsonUtils.toJsonString(message));
        return message;
    }

    @ExceptionHandler(value = {UnAuthException.class})
    public R unAuthExceptionHandler(HttpServletRequest request, HttpServletResponse response, UnAuthException unAuthException) {
        R message = new R(unAuthException.getCode(), unAuthException.getMsg(), null);
        unAuthException.printStackTrace();
        RequestUtils.deleteCookie(response, Constant.COOKIE_NAME);
        LoggerUtils.error("未授权异常={},接口响应={}", request.getRequestURL(), JsonUtils.toJsonString(message));
        return message;
    }
}
